<template>
	<view>
		<view style="margin: 100px 30px auto 30px;">
			<view v-if='showfinsh!=""' style="text-align: center; margin-bottom: 10px;">{{showfinsh}}</view>
			<view v-else style="text-align: center; margin-bottom: 10px;">看视频获取资源</view>
			<uv-button v-if='showfinsh!=""' @click="jmphome" type="success">前往资源页面>></uv-button>
			<uv-button v-else @click="showVideoAd" type="success">{{ isVideoAdLoaded ? "播放视频" : "视频加载中" }}</uv-button>
		</view>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
	import config from '../../common/config.js';
	let interstitialAd = null;
	let isInterstitialLoading = false;
	let rewardedVideoAd = null;
	let isVideoAdLoaded = ref(false);
	let modal = ref(null)
	let toast = ref(null)
	let looked = false;
	let showfinsh = ref("")

	function adconfirm() {
		showVideoAd();
	}

	function adcancel() {

	}

	function jmphome() {
		uni.navigateTo({
			url: '/pages/index/index'
		})
	}

	function showToast(params) {
		toast.value.show({
			...params,
			complete() {}
		})
	}


	onLoad((op) => {
		console.log(op)
	})

	onShow(() => {
		//激励广告
		if (wx.createRewardedVideoAd) {
			rewardedVideoAd = wx.createRewardedVideoAd({
				adUnitId: config.RewardedVideoID
			})
			rewardedVideoAd.onLoad(() => {
				console.log('激励广告加载成功');
				isVideoAdLoaded.value = true
				// if (!looked) {
				// 	looked = true;
				// 	showVideoAd();
				// }
			})
			rewardedVideoAd.onError((e) => {
				console.error('激励视频广告加载失败', e)
				showToast({
					type: 'default',
					message: e,
				})
			})
			rewardedVideoAd.onClose((e) => {
				// 用户点击了关闭广告
				isVideoAdLoaded.value = false;
				console.log("激励广告关闭", e);
				if (e && e.isEnded) {
					showfinsh.value = new Date() + "\n已观看完成视频"
					// uni.redirectTo({
					// 	url: "/pages/index/index"
					// })
				} else {
					showToast({
						type: 'default',
						message: '激励广告未观看完成',
					})
				}
			})
		}
	})

	function showVideoAd() {
		if (isVideoAdLoaded.value) {
			rewardedVideoAd.show();
		} else {
			showToast({
				type: 'default',
				title: '激励广告未加载完成',
				message: "激励广告未加载完成",
			})
		}
	}
</script>

<style>

</style>